package com.woniuxy.utils;

import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

@Component
public class ObjectRedisTemplate extends RedisTemplate<String,Object> {

    public ObjectRedisTemplate(RedisConnectionFactory rcf){
        setConnectionFactory(rcf);
        setKeySerializer(RedisSerializer.string());
        setValueSerializer(RedisSerializer.json());
        setHashKeySerializer(RedisSerializer.string());
        setHashValueSerializer(RedisSerializer.string());
        afterPropertiesSet();
    }

    public<T> T get(String key,Class<T> type){
        return (T)opsForValue().get(key);
    }

    public void addHashObject(String key,Object obj){
        Class<?> type = obj.getClass();
        //拿到所有的属性
        Field[] fields = type.getDeclaredFields();
        Map<String,Object> map = new HashMap<>();
        for(Field f : fields){
            f.setAccessible(true);
            try {
                Object value = f.get(obj);
                map.put(f.getName(),value.toString());
                f.setAccessible(false);
            } catch (IllegalArgumentException|IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        opsForHash().putAll(key,map);
    }
}
